#!/bin/bash
# run_ragen_smart.sh - 智能资源限制启动 ragen Python程序（无需root）

echo "============================================"
echo "  ragen 智能资源限制启动脚本（无root权限）"
echo "============================================"
echo "程序: python ragen/run_agent.py"
echo "目标限制: 内存 80GB | CPU 50%"
echo ""

# 配置
MEMORY_LIMIT_GB=80
CPU_LIMIT_PERCENT=50
MEMORY_LIMIT_KB=$((MEMORY_LIMIT_GB * 1024 * 1024))
PYTHON_CMD="python ragen/run_agent.py"

# 检查程序文件是否存在
if [ ! -f "ragen/run_agent.py" ]; then
    echo "错误: 找不到 ragen/run_agent.py"
    echo "请确保在正确的目录下运行此脚本"
    exit 1
fi

# 1. 设置内存限制（ulimit，始终可用）
echo "[1/4] 设置内存限制..."
ulimit -v ${MEMORY_LIMIT_KB} 2>/dev/null
ulimit -d ${MEMORY_LIMIT_KB} 2>/dev/null

# 验证ulimit设置
CURRENT_LIMIT=$(ulimit -v)
if [ "$CURRENT_LIMIT" = "unlimited" ]; then
    echo "      ⚠ 警告: 无法设置内存限制（可能需要修改系统配置）"
else
    echo "      ✓ 虚拟内存限制: ${MEMORY_LIMIT_GB}GB"
fi

# 2. 检查cpulimit
echo "[2/4] 检查 CPU 限制工具..."
CPULIMIT_CMD=""
CPU_LIMIT_AVAILABLE=false

# 检查系统安装的cpulimit
if command -v cpulimit &> /dev/null; then
    CPULIMIT_CMD="cpulimit"
    CPU_LIMIT_AVAILABLE=true
    echo "      ✓ 找到系统 cpulimit"
# 检查用户编译的cpulimit
elif [ -f "$HOME/tools/cpulimit/src/cpulimit" ]; then
    CPULIMIT_CMD="$HOME/tools/cpulimit/src/cpulimit"
    CPU_LIMIT_AVAILABLE=true
    echo "      ✓ 找到用户 cpulimit: $CPULIMIT_CMD"
else
    echo "      ✗ 未找到 cpulimit（将无法限制CPU）"
    echo ""
    echo "      【如何安装 cpulimit】"
    echo "      方法1 - 从源码编译（推荐）:"
    echo "        mkdir -p ~/tools && cd ~/tools"
    echo "        git clone https://github.com/opsengine/cpulimit.git"
    echo "        cd cpulimit && make"
    echo ""
    echo "      方法2 - 如果有sudo权限:"
    echo "        sudo apt-get install cpulimit"
    echo ""
fi

# 3. 设置进程优先级
echo "[3/4] 设置进程优先级..."
echo "      ✓ nice 值: 19（最低优先级）"

# 4. 启动程序
echo "[4/4] 启动 ragen..."
echo ""
echo "----------------------------------------"

if [ "$CPU_LIMIT_AVAILABLE" = true ]; then
    echo "使用方案: cpulimit + ulimit + nice"
    echo "资源限制: 内存 ${MEMORY_LIMIT_GB}GB | CPU ${CPU_LIMIT_PERCENT}%"
    echo "启动命令: $PYTHON_CMD"
    echo "----------------------------------------"
    echo ""
    
    # 使用cpulimit限制CPU
    # -l 50 表示限制CPU使用率为50%
    # -- 后面跟要执行的完整命令
    $CPULIMIT_CMD -l ${CPU_LIMIT_PERCENT} -- nice -n 19 $PYTHON_CMD
else
    echo "使用方案: ulimit + nice（仅限制内存，CPU无限制）"
    echo "资源限制: 内存 ${MEMORY_LIMIT_GB}GB | CPU 无限制"
    echo "启动命令: $PYTHON_CMD"
    echo "----------------------------------------"
    echo ""
    
    # 仅使用nice降低优先级
    nice -n 19 $PYTHON_CMD
fi

EXIT_CODE=$?

echo ""
echo "============================================"
echo "  ragen 程序已结束 (退出码: $EXIT_CODE)"
echo "============================================"

exit $EXIT_CODE